package com.yuanxin.chooseimage.photo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.github.chrisbanes.photoview.PhotoView;
import com.yuanxin.chooseimage.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import static android.R.attr.path;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

public class PreviewActivity extends Activity {

    private static final String TAG = "PreviewActivity";

    private ViewPager mViewPager;
    private TextView save;
    private ImageView back;

    private int showfirst;

    private String[] imgPaths = new String[]{
            "/storage/emulated/0/Pictures/Screenshots/Screenshot_2016-12-18-11-03-37.png",
            "http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg",
            "http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg"};

    //base64 使用静态变量接收，intent传递数据有限制
    public static String[] imgBase64 = new String[]{};

    private PhotoView[] mImageViews;
    private ProgressBar[] mProgressBar;
    private Boolean[] isLoad;
    private boolean isFirst = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview);

        Bundle bundle = getIntent().getExtras();
        showfirst = bundle.getInt("showfirst");
        imgPaths = bundle.getStringArray("imgPaths");
       // Log.e(TAG, "showfirst---" + showfirst + "-imgPaths-" + imgPaths);
        if (imgPaths != null && imgPaths.length > 0) {
            mImageViews = new PhotoView[imgPaths.length];
            mProgressBar = new ProgressBar[imgPaths.length];
            isLoad = new Boolean[imgPaths.length];
        } else {
            mImageViews = new PhotoView[imgBase64.length];
            mProgressBar = new ProgressBar[imgBase64.length];
            isLoad = new Boolean[imgBase64.length];
        }
        save = (TextView) findViewById(R.id.tv_save);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final int currentItem = mViewPager.getCurrentItem();
               // Log.e(TAG, "currentItem---" + currentItem);
                if (imgPaths != null && imgPaths.length > 0) {
                    if (imgPaths[currentItem].startsWith("http")) {
                        //网络
                        Glide.with(getApplicationContext())
                                .asBitmap()
                                .load(imgPaths[currentItem])
                                .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> glideAnimation) {
                                try {
                                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                    bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);
                                    saveImageToGallerys(getApplicationContext(), baos.toByteArray());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } else {
                        //本地
                        Bitmap localBitmap = getLocalBitmap(imgPaths[currentItem]);
                        saveImageToGallery(PreviewActivity.this, localBitmap);
                    }
                } else {
                    Glide.with(getApplicationContext())
                            .asBitmap()
                            .load(Base64.decode(imgBase64[currentItem], Base64.DEFAULT))
                            .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> glideAnimation) {
                            try {
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);
                                saveImageToGallerys(getApplicationContext(), baos.toByteArray());
//                                saveImageToGallerys(getApplicationContext(), bytes);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        });

        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
        mViewPager.setAdapter(new PagerAdapter() {
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View view = getLayoutInflater().inflate(R.layout.viewpager_item, null);
                PhotoView photoView = (PhotoView) view.findViewById(R.id.photoView);
                ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
                photoView.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
                container.addView(view);
                mImageViews[position] = photoView;
                mProgressBar[position] = progressBar;
                if (position == showfirst && isFirst) {
                    loadImage(position);
                    isFirst = false;
                }
                return view;
            }

            @Override
            public void destroyItem(ViewGroup container, int position,
                                    Object object) {
                container.removeView((View) object);
            }


            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }

            @Override
            public int getCount() {
                if (imgPaths != null && imgPaths.length > 0) {
                    return imgPaths.length;
                } else {
                    return imgBase64.length;
                }
            }
        });

        mViewPager.setCurrentItem(showfirst);

        mViewPager.getAdapter().notifyDataSetChanged();

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                loadImage(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        back = (ImageView) findViewById(R.id.image_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    private void loadImage(final int position) {
        if (isLoad[position] == null || !isLoad[position]) {
            mImageViews[position].setVisibility(View.GONE);
            mProgressBar[position].setVisibility(View.VISIBLE);
        } else {
            mImageViews[position].setVisibility(View.VISIBLE);
            mProgressBar[position].setVisibility(View.GONE);
        }
        if (imgPaths != null && imgPaths.length > 0) {
            if (imgPaths[position].startsWith("http")) {
                //网络
                Glide.with(PreviewActivity.this)
                        .load(imgPaths[position])
                        .fitCenter()
                        .error(R.drawable.big_default_error)
                        .into(new MySimpleTarget(position));
            } else {
                //本地
                File file = new File(imgPaths[position]);
                if (file.exists()) {
                    Glide.with(PreviewActivity.this)
                            .load(new File(imgPaths[position]))
                            .fitCenter()
                            .error(R.drawable.big_default_error)
                            .into(new MySimpleTarget(position));
                } else {
                   // Log.e(TAG, "没有找到路径");
                    mImageViews[position].setVisibility(View.VISIBLE);
                    mImageViews[position].setImageResource(R.drawable.big_default_error);
                    mImageViews[position].setScaleType(ImageView.ScaleType.CENTER);
                    mProgressBar[position].setVisibility(View.GONE);
                    isLoad[position] = true;
                }
            }
        } else {
            try{
                byte[] bytes = Base64.decode(imgBase64[position], Base64.DEFAULT);
                Glide.with(PreviewActivity.this)
                        .load(bytes)
                        .fitCenter()
                        .error(R.drawable.big_default_error)
                        .into(new MySimpleTarget(position));
            }catch (Exception e){//如果base64不正确，则会报错
                e.printStackTrace();
                mImageViews[position].setVisibility(View.VISIBLE);
                mImageViews[position].setImageResource(R.drawable.big_default_error);
                mImageViews[position].setScaleType(ImageView.ScaleType.CENTER);
                mProgressBar[position].setVisibility(View.GONE);
                isLoad[position] = true;
            }

        }
    }

    class MySimpleTarget extends SimpleTarget<Drawable> {
        private int position;
        public MySimpleTarget(int position){
            this.position = position;
        }
        @Override
        public void onResourceReady(Drawable resource, Transition<? super Drawable > glideAnimation) {
            mImageViews[position].setVisibility(View.VISIBLE);
            mImageViews[position].setImageDrawable(resource);
            mProgressBar[position].setVisibility(View.GONE);
            isLoad[position] = true;
        }

        @Override
        public void onLoadFailed(Drawable errorDrawable) {
            super.onLoadFailed(errorDrawable);
            mImageViews[position].setVisibility(View.VISIBLE);
            mImageViews[position].setImageResource(R.drawable.big_default_error);
            mImageViews[position].setScaleType(ImageView.ScaleType.CENTER);
            mProgressBar[position].setVisibility(View.GONE);
            isLoad[position] = true;
        }

    }

    /**
     * 加载本地图片
     */
    public static Bitmap getLocalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从网络取图片 http
     */
    public static Bitmap getHttpBitmap(String url) {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setConnectTimeout(0);
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 保存图片本地
     */
    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库

//        Toast.makeText(context, "本地图片保存成功---" + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
        Toast.makeText(context, "保存成功", Toast.LENGTH_LONG).show();

        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
    }

    public static void saveImageToGallerys(Context context, byte[] bytes) {
        if (bytes == null) {
            return;
        }
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bytes);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

//        Toast.makeText(context, "网络图片保存成功---" + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
        Toast.makeText(context, "保存成功", Toast.LENGTH_LONG).show();

        // 最后通知图库更新
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    }

    /**
     * 保存网络图片
     */
    public static void saveImageToGallerys(Context context, Bitmap bmp) {
        if (bmp == null) {
            return;
        }
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

//        Toast.makeText(context, "网络图片保存成功---" + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
        Toast.makeText(context, "保存成功", Toast.LENGTH_LONG).show();

        // 最后通知图库更新
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    }


}
